# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :get_robot2.py
# @Time      :2025/5/7 13:58:40
# @Author    :flower
import json
import time
import hmac
import hashlib
import base64
import urllib.parse

import requests

timestamp = str(round(time.time() * 1000))
secret = 'SEC238b8f2a899e15339701f60ef95f42421f9867faa1a10082903ec2b2c6944cbe'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)

url = f'https://oapi.dingtalk.com/robot/send?access_token=9295d0b2177891558c64c519e801adad9ca34461287d89f7ae6bfbbed6b44ded&timestamp={timestamp}&sign={sign}'


# 发送消息
def DingMessage(Content):
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 构建请求数据
    message = {
        "msgtype": "text",
        "text": {
            "content": Content
        },
        "at": {
            "atMobiles": [
                "18989454851",
            ],
            # "isAtAll": True
        }
    }
    # 对请求的数据进行json封装、定义头部文件并发送请求
    info = requests.post(url=url, data=json.dumps(message), headers=header)
    # 判断是否发送成功
    if json.loads(info.text)['errmsg'] == "ok":
        print("发送成功!")
    else:
        print(json.loads(info.text))


if __name__ == "__main__":
    # # 群机器人webhook链接
    # webhook_url = "https://oapi.dingtalk.com/robot/send?"
    # access_token = '9295d0b2177891558c64c519e801adad9ca34461287d89f7ae6bfbbed6b44ded'
    # # 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
    # secret = 'SEC238b8f2a899e15339701f60ef95f42421f9867faa1a10082903ec2b2c6944cbe'
    # # 需要发送的消息
    # Content = sys.argv[1]
    # # 是否@所有人,是输入True否则False
    # People = sys.argv[2]
    # # 调用DingMessage填入需要传递的参数发送消息
    # # 格式：python DingTalk_Alarm.py 发送的消息 True
    # DingMessage(Signature_Url(webhook_url, secret), Content, People)
    DingMessage('测试')
